#include "doubleLoopLinkList.h"

// 创建带头结点的循环双链表
LinkList CreateDoubleLoopLinkList()
{
    LinkList L = (LinkList)malloc(sizeof(LNode));
    L->next = L->prior = L;
    L->data = 0;
    return L;
}
// 头插
LinkList HeadInsert(LinkList L, Data_type value)
{
    if (L == NULL)
    {
        printf("链表为空\n");
        return NULL;
    }
    LinkList head = L;
    LinkList newNode = (LinkList)malloc(sizeof(LNode));
    newNode->data = value;
    if (newNode == NULL)
    {
        printf("内存分配失败\n");
    }
    if (head->next != head)
    {
        head->next->prior = newNode;
    }
    newNode->next = head->next;
    newNode->prior = head;
    head->next = newNode;
}
// 获取长度
int GetLength(LinkList L)
{
    LinkList head = L;
    int length = 0;
    while (head->next != L)
    {
        head = head->next;
        length++;
    }
    return length;
}
// 指定位置插入
LinkList Insert(LinkList L, int pos, Data_type value)
{
    if (L == NULL)
    {
        printf("链表为空\n");
    }

    LinkList head = L;
    if (pos < 0 || pos > GetLength(L))
    {
        printf("插入位置不合法\n");
        return NULL;
    }
    int i = 0;
    while (head->next != head)
    {
        if (i == pos)
        {
            break;
        }
        head = head->next;
        i++;
    }
    printf("%d,插入位置：%d\n", head->data, i);
    LinkList newNode = (LinkList)malloc(sizeof(LNode));
    newNode->data = value;
    if (newNode == NULL)
    {
        printf("内存分配失败\n");
    }
    if (head->next != head)
    {
        head->next->prior = newNode;
    }
    newNode->prior = head;
    newNode->next = head->next;
    head->next = newNode;
}
// 重前往后打印
void PrintDoubleLoopLinkList(LinkList L)
{
    LinkList head = L->next;
    while (head != L)
    {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}
void main()
{
    LinkList L = CreateDoubleLoopLinkList();
    HeadInsert(L, 1);
    HeadInsert(L, 2);
    HeadInsert(L, 3);
    HeadInsert(L, 4);
    PrintDoubleLoopLinkList(L);
    Insert(L, 2, 66);
    Insert(L, 4, 88);
    PrintDoubleLoopLinkList(L);
}